package com.ruili.framework.module.blacklist.service;

import com.ruili.framework.module.blacklist.domain.BlackList;
import com.ruili.framework.module.blacklist.mapper.IBlackListMapper;
import com.ruili.framework.config.RuiliConfig;
import com.ruili.framework.utils.ip.IpUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
public class BlackListService {

    @Autowired
    private IBlackListMapper iBlackListMapper;

    @Autowired
    private RuiliConfig ruiliConfig;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 判断是否在黑名单中
     *
     * @return false 不在   true 在
     */
    public boolean checkIsBlackList() {
        String ip = IpUtils.getRequestIpAddr();
        BlackList blackList = iBlackListMapper.selectByIp(ip);
        if (blackList == null) {
            return Boolean.FALSE;
        }

        if (ObjectUtils.isNotEmpty(blackList.getLockTime())
                && BooleanUtils.or(new Boolean[]{blackList.getLockForever(),
                blackList.getLockTime().after(new Date())})) {
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

    /**
     * 走一遍黑名单逻辑
     */
    public void matchBlackList() {
        String ip = IpUtils.getRequestIpAddr();
        BlackList blackList = iBlackListMapper.selectByIp(ip);
        if (ObjectUtils.isEmpty(blackList)) {
            blackList = new BlackList();
            blackList.setIp(ip);
            blackList.setLockNumber(1);
            blackList.setLockForever(Boolean.FALSE);
            blackList.setLockTime(null);
            try {
                iBlackListMapper.insert(blackList);
            } catch (Exception e) {
                logger.error("保存ip黑名单限制出错" , e);
            }
        } else {
            if (blackList.getLockForever()) {
                return;
            }

//            失败次数超过永久次数
            if (blackList.getLockNumber() >= ruiliConfig.getIpService().getForeverLimitNumber()) {
                blackList.setLockForever(true);

                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate localDate = LocalDate.parse("2999-12-01" ,dateTimeFormatter);
                ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault());
                blackList.setLockTime(Date.from(zdt.toInstant()));
                iBlackListMapper.updateLimit(blackList);
            } else {

//                失败次数超过临时次数
                Date lockTime = DateUtils.addMinutes(new Date(), ruiliConfig.getIpService().getTemporaryLimitTime());
                if (blackList.getLockNumber() >= ruiliConfig.getIpService().getTemporaryLimitNumber()) {
                    blackList.setLockTime(lockTime);
                }
                iBlackListMapper.updateLimit(blackList);
            }
        }
    }
}
